package com.example.androidtest4

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.RadioGroup
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.File
import java.io.FileOutputStream


class MainActivity3 : AppCompatActivity() {
    private var selectGender:String="未选择"
    private var AvaterFilePath: String?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main3)
        val name=findViewById<EditText>(R.id.name)
        val sno=findViewById<EditText>(R.id.sno)
        val button=findViewById<Button>(R.id.button)
        val phone=findViewById<EditText>(R.id.phone)
        val email=findViewById<EditText>(R.id.email)
        val store=findViewById<Button>(R.id.store)
        val sex=findViewById<RadioGroup>(R.id.radio)
        //点击打开拍照
        button.setOnClickListener {
           dispathTakePicture()
        }
        //去选择性别确定选择的哪一个
        sex.setOnCheckedChangeListener {
            group, checkedId ->
            when(checkedId){
                R.id.girl->selectGender="性别：女"
                R.id.boy->selectGender="性别：男"
            }
        }
        //获取选择的多个选项值
        val checkbox=mapOf(
            R.id.read to "阅读",
            R.id.shop to "购物",
            R.id.game to "游戏",
            R.id.trip to "旅游"
        )
        //保存按钮操作
        store.setOnClickListener {
            val intent= Intent()
            val nameInfo=name.getText().toString().ifEmpty { "未输入姓名" }
            val snoInfo=sno.getText().toString()
            val emailInfo=email.getText().toString()
            val phoneInfo=phone.getText().toString()
            val sexInfo=selectGender//获取选择的性别
            val CheckBoxMap=mutableListOf<String>()
            for((id,text)in checkbox){
                val select=findViewById<CheckBox>(id)
                if(select.isChecked){
                    CheckBoxMap.add(text)//选择好爱好之后把他记录添加
                }
            }
            //判断路径是否为空
            if(AvaterFilePath!=null){
                intent.putExtra("IMAGE_PATH",AvaterFilePath)
            }
            val hobby=CheckBoxMap.joinToString(separator = "、")//爱好的最终值里面加个分号
            val info=arrayOf(nameInfo,snoInfo,emailInfo,phoneInfo,sexInfo,hobby)//以数组的形式传回多个值
            intent.putExtra(FIRST_MSG,info)
            setResult(RESULT_OK,intent)
            Log.d("存储数据","姓名：$nameInfo")
            finish()
        }
        //取消按钮操作
        val cancel=findViewById<Button>(R.id.cancel)
        cancel.setOnClickListener {
            val intent=Intent()
            setResult(RESULT_OK,intent)
            finish()
        }
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val imagePicture=findViewById<ImageView>(R.id.imageView2)
        if(requestCode==1&&resultCode==RESULT_OK){
            val imageBitmap=data?.extras?.get("data")as Bitmap
            imageBitmap.let{
                imagePicture.setImageBitmap(it)
                AvaterFilePath=saveBitmapToLocal(it)//获取图片地址函数
                Toast.makeText(this, "拍照成功", Toast.LENGTH_SHORT).show()
            }
        }
    }
    //打开相机
    private fun dispathTakePicture(){
        val picIntent=Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if(intent.resolveActivity(packageManager)!=null){//这里注意打不开相机因为这里不要用自己设置的intent！！！！！
            startActivityForResult(picIntent,1)
        }
    }
    //保存图片的函数，获取图片地址然后传回去接收后面的调用
    private fun saveBitmapToLocal(bitmap: Bitmap):String?{
        //创建文件路径
        val file=File(filesDir,"avatar_${System.currentTimeMillis()}.png")
        //将bitmap写入文件
        val outputStream= FileOutputStream(file)
        //压缩图片
        bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream)
        outputStream.flush()//刷新缓存区
        outputStream.close()//关闭流
        return file.absolutePath//直接把图片地址传回去

    }


}